package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import com.ideabove.adapter.SongAdapter;
import com.ideabove.data.Folder;
import com.ideabove.data.PlayItem;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.module.SongSearchMd.BackToWhere;
import com.ideabove.radio.service.PlayBackService;
import com.ideabove.util.ConnectThread;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FolderDetailMd  extends ModuleAbs{	
	ArrayList<PlayItem> songArr = null;
	ListView songList = null;
	SongAdapter adapter = null;
	Folder currentFolder = null;
	
	public int mode = 0;
	public int NORMAL_FOLDER = 1;
	public int LIKE_FOLDER = 2;
	
	
	public void init(MainActivity activity){
		super.init(activity);		
	}
	
	public interface ShowFolersCallback{
		public void callback(ListView listView);
	}
	
	
	public void showFolderDetail(final Folder folder ,final ShowFolersCallback callback){
		mode = NORMAL_FOLDER;
		final String folderId = folder.getFolder_id();
		currentFolder = folder;
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		
		
		LayoutInflater layoutInflater = (LayoutInflater) 
        activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_folder_detail, null);	
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert); 
		
		
		// 빽버튼
//		MdManager.setBackButton(new MdManager.BackButton() {
//			
//			@Override
//			public void backToTheWorld() {
//				// TODO Auto-generated method stub
//				activity.folderMd.showFolderList();
//			}
//		});
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				
				// complete call back;
				if(callback != null){
					callback.callback(songList);
					return;
				}
				
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
				
				
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				
				// complete call back;
				if(result == null && callback != null){
					callback.callback(songList);
					return;
				}	
				
				TextView folder_detail_title = (TextView)activity.findViewById(R.id.folder_detail_title);
				folder_detail_title.setText("폴더리스트 > " + folder.getTitle());				
				
				// 오른쪽 상단 버튼
				FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
				btn_top_left_btn_wrap.setVisibility(View.GONE);		
				
				LinearLayout folder_detail_two_btns = (LinearLayout)activity.findViewById(R.id.folder_detail_two_btns);
				folder_detail_two_btns.setVisibility(View.VISIBLE);
				
				ImageView under_line = (ImageView)activity.findViewById(R.id.under_line);
				under_line.setVisibility(View.VISIBLE);
				
				TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
				btn_top_right_text.setText("Edit");
				btn_top_right_text.setTextColor(activity.getResources().getColor(R.color.white));
				
				// Edit 버튼 클릭
				ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
				btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																				
							// code							
							adapter.setEditMode(true);
							adapter.notifyDataSetChanged();
							
							LinearLayout folder_detail_two_btns = (LinearLayout)activity.findViewById(R.id.folder_detail_two_btns);
							folder_detail_two_btns.setVisibility(View.GONE);
							
							FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
							btn_top_left_btn_wrap.setVisibility(View.GONE);
							
							ImageView under_line = (ImageView)activity.findViewById(R.id.under_line);
							under_line.setVisibility(View.GONE);
							
							// done 클릭
							TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
							btn_top_right_text.setText("Done");
							ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
							btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {

								@Override
								public boolean onTouch(View v, MotionEvent event) {
									// TODO Auto-generated method stub
									ImageView view = (ImageView)v;
									if(event.getAction() == MotionEvent.ACTION_DOWN){
										view.setPadding(2, 2, 2, 2);
										view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
									}else if(event.getAction() == MotionEvent.ACTION_UP){
										
										// Logic
										FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
										btn_top_left_btn_wrap.setVisibility(View.GONE);	
										showFolderDetail(currentFolder , null);
										
										// 갯수수정
										TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
										folder_detail_song_cnt.setText("["+songArr.size()+"]");
										
										view.setPadding(0, 0, 0, 0);
										view.setColorFilter(0x00000000, Mode.SRC_OVER);
									}else{
										view.setPadding(0, 0, 0, 0);
										view.setColorFilter(0x00000000, Mode.SRC_OVER);									
									}
									return true;
								}
								
							});
							
							
							
							
							// 곡 정보 편집
							songList.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> parentView, View view, int position, long id) {
									// TODO Auto-generated method stub
//									Log.e("#setOnItemClickListener#####", "######" + view.getTag());
									activity.songEditMd.showSongEdit(folder , (PlayItem)view.getTag(), null);
								}
								
							});
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				// 왼쪽 상단 버튼
//				TextView btn_top_left_text = (TextView)activity.findViewById(R.id.btn_top_left_text);
//				btn_top_left_text.setText("Back");
//				
				// 선곡하기
				ImageView folder_de_btn_listen_each = (ImageView)activity.findViewById(R.id.folder_de_btn_listen_each);
				folder_de_btn_listen_each.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
									
							// 선곡하기를 보여준다 빽했을때 다시 이리루 호출함.
							activity.songSearchMd.showSongSearch(new BackToWhere() {
								
								@Override
								public void goBack() {
									// TODO Auto-generated method stub
									showFolderDetail(folder, callback);
								}
							});
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				songArr = (ArrayList<PlayItem>)result;				
				if(songArr == null){
					return;
				}
				
				adapter = new SongAdapter(activity.getApplicationContext(),songArr, activity);				
				songList = (ListView)activity.findViewById(R.id.listv_edit_folders_de);				
				songList.setAdapter(adapter);
				songList.setDivider(null);
				

				// 갯수 수정
				TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
				folder_detail_song_cnt.setText("[" + adapter.getCount() + "]");
				
				songList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parentView, View view, int position, long id) {
						// TODO Auto-generated method stub
						PlayItem playItem = (PlayItem)songArr.get(position);
						final String link = playItem.getLink();
						
						// playlist song play
						AlertDialog.Builder aDialog = new AlertDialog.Builder(activity);
						aDialog.setMessage("리스트에 있는 곡들을 재생 하시겠습니까?");
						aDialog.setPositiveButton("재생", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
								 Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_FOCUS_PLAYITEM_TO_PLAY);
								 
									 HashMap<String, Object> dataToSend = new HashMap<String, Object>();
									 dataToSend.put("link", link);									 
									 dataToSend.put("array", songArr.clone());
								 
								 msg.obj = dataToSend;								 
								 activity.sendMessageToService(msg);
								 
								 hideViewFlipper();
							 }
						});
						aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
							 }
						});
						aDialog.show();
						
					}
					
				});
				
				// 모두듣기 버튼 클릭
				ImageView folder_de_btn_listen_all = (ImageView)activity.findViewById(R.id.folder_de_btn_listen_all);
				folder_de_btn_listen_all.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							if(songArr != null && ((ArrayList)songArr).size() > 0){
								Toast.makeText(activity.getApplicationContext(), "스튜디오의 전곡이 플레이 됩니다\n" +
										"잠시만 기다려 주세요\n(Like 폴더제외)", Toast.LENGTH_LONG).show();
								
								hide();
								
								Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_GET_ALL_FOLDER_TO_PLAY);
								msg.obj = songArr;
								activity.sendMessageToService(msg);
							}else{
								Toast.makeText(activity.getApplicationContext(), "폴더에 모아 놓은 곡들이 없습니다.\n" +
										"선곡하기 버튼을 눌러주세요", Toast.LENGTH_LONG).show();
							}
							
							
															
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				
				// complete call back;
				if(callback != null){
					callback.callback(songList);
				}		
								
			}
			
			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/folderInfo.php");
//				parameter 
//				일반 폴더 ( type : ‘normal’, uId : 사용자ID , fId : 폴더ID )
//				b. 좋아요 폴더 (type : ‘like’, uId : 사용자ID )


				String userId = activity.facebookMd.getBonoUserId();
				
				if(TextUtils.isEmpty(userId) || TextUtils.isEmpty(folderId)){
					throw new Exception("parameter error");
				}
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				
				
				if(!"0".equals(folderId)){
					params.add(new BasicNameValuePair("type", "normal"));
					params.add(new BasicNameValuePair("uId", userId));
					params.add(new BasicNameValuePair("fId", folderId));
				}else{
					params.add(new BasicNameValuePair("type", "like"));
					params.add(new BasicNameValuePair("uId", userId));					
				}
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);		
				
				if(jsonStr != null && jsonStr.length() > 0){

					ArrayList<PlayItem> songArr = new ArrayList<PlayItem>();
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");

					
//					folder_id : 폴더ID
//			        b. cpost_id : 포스트 ID
//			        c. title:곡제목
//			        d. link : 유투브 링크
//			        e. thumb_url : 썸네일 URL 
//					f.	user_id : 포스트 올린 사용자ID
//					g.	isLikeIdx : 해당 포스트 좋아요 유무 ( 0 : 안함, 1 : 좋아요 )

					for (int i = 0; i < resultArray.length(); i++) {
						PlayItem song = new PlayItem();
						JSONObject jObj = resultArray.getJSONObject(i);
						song.setFolderId(jObj.getString("folder_id").toString());
						song.setCpost_id(jObj.getString("cpost_id").toString());
						song.setTitle(jObj.getString("title").toString());
						song.setLink(jObj.getString("link").toString());
						song.setThumbUrl(jObj.getString("thumb_url").toString());
						song.setUserId(jObj.getString("user_id").toString());
						song.setpUid(jObj.getString("pUid").toString());
						song.setIsLikeIdx(jObj.getString("isLikeIdx").toString());
						
						songArr.add(song);
					}				
					resultSet.setResult(songArr);	
				}
			}
		}).start(); 
	}
	
	
	public void showLikeFolderDetail(final Folder folder ,final ShowFolersCallback callback){
		mode = LIKE_FOLDER;
		final String folderId = folder.getFolder_id();
		currentFolder = folder;
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		
		
		LayoutInflater layoutInflater = (LayoutInflater) 
        activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_like_folder_detail, null);	
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert); 
	
		
		// 빽버튼
//		MdManager.setBackButton(new MdManager.BackButton() {
//			
//			@Override
//			public void backToTheWorld() {
//				// TODO Auto-generated method stub
//				activity.folderMd.showFolderList();
//			}
//		});
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog(); 
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE);
				String clubName 	= prefs.getString(FacebookMd.PREFERENCE_USER_CLUB_NAME, "");
				
				
				TextView folder_detail_title = (TextView)activity.findViewById(R.id.folder_detail_title);
				folder_detail_title.setText("폴더리스트 > " + folder.getTitle());
				
				// 오른쪽 상단 버튼
				FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
				btn_top_left_btn_wrap.setVisibility(View.GONE);	
				
				FrameLayout btn_top_right_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_right_btn_wrap);
				btn_top_right_btn_wrap.setVisibility(View.VISIBLE);	
				
				LinearLayout folder_detail_two_btns = (LinearLayout)activity.findViewById(R.id.folder_detail_two_btns);
				folder_detail_two_btns.setVisibility(View.VISIBLE);
				
				View under_line = (View)activity.findViewById(R.id.under_line);
				under_line.setVisibility(View.VISIBLE);
				
				// Edit Button
				TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
				btn_top_right_text.setText("Edit");
				btn_top_right_text.setTextColor(activity.getResources().getColor(R.color.white));

				// Edit Button
				ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
				btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																				
							// code							
							adapter.setEditMode(true);
							adapter.notifyDataSetChanged();
							TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
							btn_top_right_text.setText("Done");
							
							ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
							btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {

								@Override
								public boolean onTouch(View v, MotionEvent event) {
									// TODO Auto-generated method stub
									ImageView view = (ImageView)v;
									if(event.getAction() == MotionEvent.ACTION_DOWN){
										view.setPadding(2, 2, 2, 2);
										view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
									}else if(event.getAction() == MotionEvent.ACTION_UP){
										
										// Logic
										FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
										btn_top_left_btn_wrap.setVisibility(View.GONE);	
										showLikeFolderDetail(currentFolder , null);
										
										// 갯수수정
										TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
										folder_detail_song_cnt.setText("["+songArr.size()+"]");
										
										view.setPadding(0, 0, 0, 0);
										view.setColorFilter(0x00000000, Mode.SRC_OVER);
									}else{
										view.setPadding(0, 0, 0, 0);
										view.setColorFilter(0x00000000, Mode.SRC_OVER);									
									}
									return true;
								}
								
							});
							
							LinearLayout folder_detail_two_btns = (LinearLayout)activity.findViewById(R.id.folder_detail_two_btns);
							folder_detail_two_btns.setVisibility(View.GONE);
							
							View under_line = (View)activity.findViewById(R.id.under_line);
							under_line.setVisibility(View.GONE);
							
							// 플레이 시키는거 취소
							songList.setOnItemClickListener(null);
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				// 왼쪽 상단 버튼
				TextView btn_top_left_text = (TextView)activity.findViewById(R.id.btn_top_left_text);
				btn_top_left_text.setText("Back");
				
				ImageView btn_top_left_img = (ImageView)activity.findViewById(R.id.btn_top_left_img);
				btn_top_left_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																				
							// code
							activity.folderMd.showFolderList();
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				songArr = (ArrayList<PlayItem>)result;				
				adapter = new SongAdapter(activity.getApplicationContext(),songArr, activity);				
				songList = (ListView)activity.findViewById(R.id.listv_edit_folders_de);				
				songList.setAdapter(adapter);
				songList.setDivider(null);
				
				
				// 갯수 수정				
				TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
				folder_detail_song_cnt.setText("["+songArr.size()+"]");
				
				songList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parentView, View view, int position, long id) {
						// TODO Auto-generated method stub
						PlayItem playItem = (PlayItem)songArr.get(position);
						final String link = playItem.getLink();
						
						// playlist song play
						AlertDialog.Builder aDialog = new AlertDialog.Builder(activity);
						aDialog.setMessage("리스트에 있는 곡들을 재생 하시겠습니까?");
						aDialog.setPositiveButton("재생", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
								 Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_FOCUS_PLAYITEM_TO_PLAY);
								 
									 HashMap<String, Object> dataToSend = new HashMap<String, Object>();
									 dataToSend.put("link", link);
									 dataToSend.put("array", songArr.clone());
								 
								 msg.obj = dataToSend;								 
								 activity.sendMessageToService(msg);
								 
								 hideViewFlipper();
							 }
						});
						aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
							 public void onClick(DialogInterface dialog, int which) {
							 }
						});
						aDialog.show();
						
					}
					
				});
				
				// 모두듣기 버튼 클릭
				ImageView folder_de_btn_listen_all = (ImageView)activity.findViewById(R.id.folder_de_btn_listen_all);
				folder_de_btn_listen_all.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){

							
							if(songArr != null && ((ArrayList)songArr).size() > 0){
								Toast.makeText(activity.getApplicationContext(), "스튜디오의 전곡이 플레이 됩니다\n" +
										"잠시만 기다려 주세요\n(Like 폴더제외)", Toast.LENGTH_LONG).show();
								
								hide();
								
								Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_GET_ALL_FOLDER_TO_PLAY);
								msg.obj = songArr;
								activity.sendMessageToService(msg);
							}else{
								Toast.makeText(activity.getApplicationContext(), "폴더에 모아 놓은 곡들이 없습니다.\n" +
										"선곡하기 버튼을 눌러주세요", Toast.LENGTH_LONG).show();
							}
							
															
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				
				// complete call back;
				if(callback != null){
					callback.callback(songList);
				}		
								
			}
			
			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub					
				
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/folderInfo.php");
//				parameter 
//				일반 폴더 ( type : ‘normal’, uId : 사용자ID , fId : 폴더ID )
//				b. 좋아요 폴더 (type : ‘like’, uId : 사용자ID )


				String userId = activity.facebookMd.getBonoUserId();
				
				if(TextUtils.isEmpty(userId) || TextUtils.isEmpty(folderId)){
					throw new Exception("parameter error");
				}
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				
				
				if(!"0".equals(folderId)){
					params.add(new BasicNameValuePair("type", "normal"));
					params.add(new BasicNameValuePair("uId", userId));
					params.add(new BasicNameValuePair("fId", folderId));
				}else{
					params.add(new BasicNameValuePair("type", "like"));
					params.add(new BasicNameValuePair("uId", userId));					
				}
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);		
				
				if(jsonStr != null && jsonStr.length() > 0){

					ArrayList<PlayItem> songArr = new ArrayList<PlayItem>();
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");

					// normal
//					a. folder_id : 폴더ID
//			        b. cpost_id : 포스트 ID
//			        c. title:곡제목
//			        d. link : 유투브 링크
//			        e. thumb_url : 썸네일 URL 
//					f. user_id : 포스트 올린 사용자ID
//					g. isLikeIdx : 해당 포스트 좋아요 유무 ( 0 : 안함, 1 : 좋아요 )
					
					// like
//					"cpost_id":"5723",
//					"user_id":"944",
//					"pUid":"944",
//					"folder_id":"0",
//					"title":"Sentimental Scenery_ Oriental Snow",
//					"link":"7hZT35GPoRA",
//					"thumb_url":"http:\/\/i.ytimg.com\/vi\/7hZT35GPoRA\/mqdefault.jpg",
//					"isLikeIdx":"1",
//					"favor_time":"2013-02-01 16:33:05"

					for (int i = 0; i < resultArray.length(); i++) {
						PlayItem song = new PlayItem();
						JSONObject jObj = resultArray.getJSONObject(i);
						song.setFolderId(jObj.getString("folder_id").toString());
						song.setCpost_id(jObj.getString("cpost_id").toString());
						song.setTitle(jObj.getString("title").toString());
						song.setLink(jObj.getString("link").toString());
						song.setThumbUrl(jObj.getString("thumb_url").toString());
						song.setUserId(jObj.getString("user_id").toString());
						song.setIsLikeIdx(jObj.getString("isLikeIdx").toString());
						song.setpUid(jObj.getString("pUid").toString());						
						
						// like 폴더일경우
//						if("0".equals(folderId)){
//							 
//							song.setpUid(jObj.getString("pUid").toString());
//							Log.e("####setpUid", "####" + song.getpUid());
//						}
						songArr.add(song);
					}				
					resultSet.setResult(songArr);	 
				}else{
					throw new Exception();
				}
			}
		}).start(); 
	}
	
	public void requestRemoveSong(final View viewForRemove, final int postition, final PlayItem song){
		if(mode == LIKE_FOLDER){
			requestRemoveLikeSong(viewForRemove, postition, song);
		}else{
			requestRemoveNormalSong(viewForRemove, postition, song);
		}
	}
	
	public void requestRemoveNormalSong(final View viewForRemove, final int postition, final PlayItem song){
		
			int timeout = 3;
			new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
				
				@Override
				public void fail(Object result) {
					// TODO Auto-generated method stub

					AlertDialog.Builder ab = new AlertDialog.Builder(activity);
					ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
					ab.setPositiveButton("ok", null);  
					ab.show();
				}
				
				@Override
				public void sucess(Object result){

					removeListItem(viewForRemove, postition);				
				}
							
				public void removeListItem(View rowView, final int positon ) {
			        // TODO Auto-generated method stub
					songArr.remove(positon);		
	                adapter.notifyDataSetChanged();
	                TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
					folder_detail_song_cnt.setText("["+songArr.size()+"]");
			    }
				
				@Override
				public void threadProcess(ConnectThread resultset) throws Exception {
					// TODO Auto-generated method stub					
					
					HttpClient client = NetWorkManager.getHttpConnection();    
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);		

					HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/delSong.php");
//					2.	parameter :
//					a.	uId : 사용자 ID
//					b.	cId : 곡 ID
//					실패 : 0 , 성공 : 1

					String uId = activity.facebookMd.getBonoUserId();		
					String cId = song.getCpost_id();
								
					
					List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					params.add(new BasicNameValuePair("uId", uId));
					params.add(new BasicNameValuePair("cpostId", cId));
									
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);  

					InputStream in = responsePOST.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					String jsonStr = str.toString();
//					Log.e("#########http://14.63.217.155/radio_bonosound/delSong.php", "[result]:" + jsonStr);
//					Log.e("#########param", "[result]:" + params);
					
					
				}
			}).start(); 
	}
	
		
	
	public void requestRemoveLikeSong(final View viewForRemove, final int postition, final PlayItem song){
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab = new AlertDialog.Builder(activity);
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				removeListItem(viewForRemove, postition);				
			}
						
			public void removeListItem(View rowView, final int positon ) {
		        // TODO Auto-generated method stub
				songArr.remove(positon);		
                adapter.notifyDataSetChanged();
                TextView folder_detail_song_cnt = (TextView)activity.findViewById(R.id.folder_detail_song_cnt);
				folder_detail_song_cnt.setText("["+songArr.size()+"]");
		    }
			
			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);		

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/reqLike.php");
//				2.	parameter :
//				a.  type : 2
//				a.	uId : 사용자 ID
//				b.	cId : 곡 ID
//				c.  pUid : 올린사람 ID
//				실패 : 0 , 성공 : 1

				String uId = activity.facebookMd.getBonoUserId();		
				String cId = song.getCpost_id();
				String pUid = song.getpUid();				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("type", "2"));
				params.add(new BasicNameValuePair("uId", uId));
				params.add(new BasicNameValuePair("cId", cId));
				params.add(new BasicNameValuePair("pUid", pUid));
								
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########http://14.63.217.155/radio_bonosound/reqLike.php", "[result]:" + jsonStr);
//				Log.e("#########param", "[result]:" + params);
				
				
			}
		}).start(); 
	}
	
	public void hideViewFlipper(){
		hide();
	}
	
	@Override
	public void showMd() {
		// TODO Auto-generated method stub
		View btn_top_left_btn_wrap = (View)activity.findViewById(R.id.btn_top_left_btn_wrap);
		btn_top_left_btn_wrap.setVisibility(View.GONE);
		
		View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
		btn_top_right_btn_wrap.setVisibility(View.VISIBLE);
	}
	
	@Override
	public void backMd() {
		// TODO Auto-generated method stub
		
		if(adapter != null && adapter.isEditMode()){
			// Logic
			FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
			btn_top_left_btn_wrap.setVisibility(View.GONE);	

			View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
			btn_top_right_btn_wrap.setVisibility(View.VISIBLE);
			
			showFolderDetail(currentFolder , new ShowFolersCallback() {
				
				@Override
				public void callback(ListView listView) {
					// TODO Auto-generated method stub
					activity.folderMd.showFolderList();
				}
			});
		}else{
		
			activity.folderMd.showFolderList();
		}
		
	}
		
}
